package com.daigou.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daigou.constants.CommonConstants;
import com.daigou.dto.AjaxResult;
import com.daigou.dto.OrderQuery;
import com.daigou.dto.PageInfo;
import com.daigou.dto.ServiceResult;
import com.daigou.enums.OrderStatusEnum;
import com.daigou.model.Customer;
import com.daigou.model.Order;
import com.daigou.model.Pay;
import com.daigou.model.Product;
import com.daigou.model.Shop;
import com.daigou.model.ShopCustomer;
import com.daigou.service.CustomerService;
import com.daigou.service.OrderService;
import com.daigou.service.PayService;
import com.daigou.service.ProductService;
import com.daigou.service.ShopService;
import com.daigou.tools.GenerateUUID;

@Controller
public class OrderController {
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private PayService payService;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private ShopService shopService;
	
	@Autowired
	private CustomerService customerService;
	/**
	 * 购物车
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/product/{id}/shop-car",method = RequestMethod.GET)
    public String toShoppingCarPage(HttpServletResponse response,
    		HttpServletRequest request,
    		Model model,
    		@PathVariable("id")Long id){
		LOGGER.info("进入购物车{}",id);
		Product product = productService.selectByPrimaryKey(id);
		Cookie[] cookies = request.getCookies();
		String productArray = null;
		if (null == cookies) {
			LOGGER.info("没有cookie==============");
		} else {
			//遍历cookie如果找到登录状态则返回true执行原来controller的方法
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CommonConstants.SHOP_CAR+product.getShopId())) {
					productArray = cookie.getValue();
					LOGGER.info("cookie(productArray)=============="+productArray);
					continue;
				}
			}
		}
		List<Product> productList = null;
		if(productArray != null){
			productList = productService.selectByIds(productArray);
			if(!productArray.contains(id.toString())){
				productArray = productArray + ","+id;
			}
		}else{
			productArray = id.toString();
		}
		//设置cookie存储订单的id
		Cookie cookie = new Cookie(CommonConstants.SHOP_CAR+product.getShopId(),productArray);//创建新cookie
        cookie.setMaxAge(24 * 60 * 30 * 365 * 10);//设置存在时间
        cookie.setPath("/");//设置作用域
        response.addCookie(cookie);//将cookie添加到response的cookie数组中返回给客户端
        if(productList == null){
        	productList = new ArrayList<Product>();
        }
		productList.add(product);
		model.addAttribute("productList", productList);
		LOGGER.info("进入购物车{}",id);
		return "/shop/app/shop_car";
    }
	/**
	 * 进入订单详情页面
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/{id}/details",method = RequestMethod.GET)
    public String toOrderDetailsPage(HttpServletRequest request,Model model,@PathVariable("id")Long id){
		LOGGER.info("进入订单详情页面{}",id);
		Order order = orderService.selectByPrimaryKey(id);
		List<Pay> payList = payService.selectByOrderId(order.getShopId(), order.getId());
		model.addAttribute("order", order);
		model.addAttribute("payList", payList);
		Shop shop = shopService.selectByPrimaryKey(order.getShopId());
		model.addAttribute("shop", shop);
		BigDecimal payTotalAmount = BigDecimal.ZERO;
		if(payList != null && payList.size() > 0){
			for(Pay payTmp:payList){
				if(payTmp.getStatus() != 0){
					payTotalAmount = payTotalAmount.add(payTmp.getPayMoney());
				}
			}
		}
		model.addAttribute("payTotalAmount", payTotalAmount);
		Cookie[] cookies = request.getCookies();
		String loginName = "0";
		if (null == cookies) {
			LOGGER.info("没有cookie==============");
		} else {
			//遍历cookie如果找到登录状态则返回true执行原来controller的方法
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals(CommonConstants.LOGIN_NAME)) {
					loginName = cookie.getValue();
					LOGGER.info("cookie(loginName)=============="+loginName);
					continue;
				}
			}
		}
		model.addAttribute("loginName", loginName);
		return "/shop/app/order_details";
    }
	/**
	 * 订单状态修改
	 * @return
	 */
	@RequestMapping(value = "/order-update-status",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult orderUpdateStatus(HttpServletRequest request,@RequestBody Order order){
		try{
			//User user = (User)request.getAttribute(CommonConstants.USER_INFO);
			//order.setModifierId(user.getId());
			order.setModifiedTime(new Date());
			order.setPrice(null);
			order.setNum(null);
			order.setTotalAmount(null);
			order.setPayAmount(null);
			order.setDr(null);
			int result = orderService.updateByPrimaryKeySelective(order);
			if(result == 0){
				return new AjaxResult(false,"订单更新失败,请刷新后重试!");
			}
	        return new AjaxResult(true,"订单更新成功!");
		}catch(Exception ex){
			return new AjaxResult(false,ex.getMessage());
		}
    }
	/**
	 * 立即购买
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/order/product/{id}/go-buy",method = RequestMethod.GET)
    public String toOrderPage(HttpServletResponse response,Model model,@PathVariable("id")Long id){
		LOGGER.info("进入立即购买{}",id);
		Product product = productService.selectByPrimaryKey(id);
		if(product != null){
			Order order = new Order();
			//立即购买，已经有订单号了，给到前端
			order.setId(GenerateUUID.generateUUID());
			order.setProductId(product.getId());
			order.setProductName(product.getName());
			order.setSpec(product.getSpec());
			order.setCate(product.getCate());
			order.setBrand(product.getBrand());
			order.setProductionPlace(product.getProductionPlace());
			order.setPicMain(product.getPicMain());
			order.setPrice(product.getSalePrice());
			order.setTotalAmount(product.getSalePrice());
			//新建待确认
			order.setStatus(OrderStatusEnum.NEW_ORDER.getCode());
			//0，未支付
			order.setPayStatus(0);
//			//设置cookie存储订单的id
//			Cookie cookie = new Cookie("go-buy-order-id",order.getId().toString());//创建新cookie
//	        cookie.setMaxAge(24 * 60);// 设置存在时间为5分钟
//	        cookie.setPath("/");//设置作用域
//	        response.addCookie(cookie);//将cookie添加到response的cookie数组中返回给客户端
			model.addAttribute("order", order);
			model.addAttribute("product", product);
		}
		LOGGER.info("进入订单{}",id);
		return "/shop/app/order";
    }
	/**
	 * 提交订单
	 * @return
	 */
	@RequestMapping(value = "/order",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult order(HttpServletRequest request,@RequestBody Order order){
		Shop shop = shopService.selectByPrimaryKey(order.getShopId());
		order.setShopId(shop.getId());
		order.setShopName(shop.getName());
		//通过客户查找业务员
		ShopCustomer customer = customerService.selectByShopIdAndMobile(order.getShopId(), Long.parseLong(order.getBuyerCode()));
		//增加订单类型：代下单，客户下单
		if(customer != null && customer.getBusinessId() != null){
			order.setCreatorId(customer.getBusinessId());
		}else{
			//默认100是没有任何归属的数据
			order.setCreatorId(Customer.NO_BUSINESS);
		}
		order.setCreatedTime(new Date());
		try{
			ServiceResult serviceResult = orderService.insertOrUpdate(order);
	        return new AjaxResult(serviceResult);
		}catch(Exception ex){
			return new AjaxResult(false,ex.getMessage());
		}
    }
	/**
	 * 订单列表
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{shopCode}/{loginName}/order/list",method = RequestMethod.GET)
    public String toMyOrderListPage(HttpServletRequest request,Model model,
    		@PathVariable("shopCode")String shopCode,
    		@PathVariable("loginName")String loginName){
		LOGGER.info("进入订单列表{}",loginName);
		//User userDb = userService.selectByLoingName(loginName);
		Shop shop = shopService.selectByCode(shopCode);
		OrderQuery orderQuery = new OrderQuery();
		orderQuery.setShopId(shop.getId());
		orderQuery.setStatus("678");
		orderQuery.setPayStatus("123");
		PageInfo<Order> pageInfo = orderService.selectByCondition(orderQuery);
		//待付款
		List<Order> orderList1 = new ArrayList<Order>();
		//待发货
		List<Order> orderList2 = new ArrayList<Order>();
		//待收货
		List<Order> orderList3 = new ArrayList<Order>();
		List<Order> orderList4 = new ArrayList<Order>();
		for(Order order:pageInfo.getRows()){
			//取消
			if(order.getStatus().equals(OrderStatusEnum.CANCEL.getCode())){
				orderList4.add(order);
			}
			//退款退货
			else if(order.getStatus().equals(OrderStatusEnum.REFOUND.getCode())){
				orderList4.add(order);
			}
			//待付款
			if(order.getPayStatus().equals(0)||order.getPayStatus().equals(1)){
				orderList1.add(order);
			}
			//待发货
			else if(order.getStatus().equals(OrderStatusEnum.CONFIRM_PACKAGING.getCode())){
				orderList2.add(order);
			}
			//待收货
			else if(order.getStatus().equals(OrderStatusEnum.SENDED.getCode())){
				orderList3.add(order);
			}
			//其他
			else{
				orderList4.add(order);
			}
		}
		model.addAttribute("orderList", pageInfo.getRows());
		model.addAttribute("orderList1", orderList1);
		model.addAttribute("orderList2", orderList2);
		model.addAttribute("orderList3", orderList3);
		model.addAttribute("orderList4", orderList4);
		return "/shop/app/my_order";
    }
}
